import { userAdd, userUpdate } from "@/services/userMsg";
import { deptList } from "@/services/deptMsg";
import { roleList } from "@/services/roleMsg";
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect
} from "@ant-design/pro-components";
import { Button, Col, Form, Row, message } from "antd";
import React, { useImperativeHandle, useState } from "react";

const ItemOption = React.forwardRef((props: any, ref) => {
  const { refreshList } = props;
  const [form] = Form.useForm<any>();
  const [modalOpen, setModalOpen] = useState(false);
  const [modItem, setModItem] = useState<any>(null);
  const handleModalShow = async (row?: any) => {
    setModItem(row || null);
    if (row) {
      form.setFieldsValue({
        ...row
      });
    }
    setModalOpen(!modalOpen);
  };
  const handleSelectDept = async (value:any,node:any) => {
    console.log(node?.children?.length,"node?.children?.length")
    if (node?.children?.length > 0) {
      // 阻止选择非叶子节点
      return false;
    }
    // 处理选择逻辑
    console.log('选择的值:', value);
  }

  useImperativeHandle(ref, () => ({
    handleModalShow,
  }));
  return (
    <ModalForm
      title={modItem?.id ? "修改用户" : "新增用户"}
      width={600}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnHidden: true,
        onCancel: () => setModalOpen(false),
        centered: true,
        maskClosable: false,
      }}
      open={modalOpen}
      submitter={{
        render: (props) => {
          let optBtns: any = [
            <Button
              className="base-button"
              key="cancel"
              onClick={() => setModalOpen(false)}
            >
              取消
            </Button>,
            <Button
              className="base-button"
              type="primary"
              key="submit"
              onClick={() => props.form?.submit?.()}
            >
              确定
            </Button>,
          ];
          return optBtns;
        },
      }}
      onFinish={async (values) => {
        const sendData = {
          ...values,
          // roleIds:values.roleIds.join(',')
        };
        let res = null;
        if (modItem?.userId) {
          //编辑
          res = await userUpdate({
            ...sendData,
            userId: modItem.userId,
          });
        } else {
          //添加
          res = await userAdd(sendData);
        }
        if (res?.code === 200) {
          message.success("操作成功");
          refreshList();
          setModalOpen(false);
        }
        return true;
      }}
    >
    
      <Row gutter={20}>
        <Col span={12}>
          <ProFormText
            name="userName"
            label="用户账号"
            fieldProps={{
              maxLength: 100,
              showCount: true,
            }}
            rules={[
              {
                required: true,
                message: "请输入用户名称",
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <ProFormSelect
            name="sex"
            label="用户性别"
            placeholder="请选择用户性别"
            rules={[
              {
                required: true,
                message: "请选择用户性别",
              },
            ]}
            options={[
              {
                label: "男",
                value: 1,
              },
              {
                label: "女",
                value: 2,
              }
            ]}
          />
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={12}>
          <ProFormText
            name="nickName"
            label="用户昵称"
            fieldProps={{
              maxLength: 100,
              showCount: true,
            }}
            placeholder="请输入用户昵称"
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name="phonenumber"
            label="用户手机号"
            fieldProps={{
              maxLength: 11,
              showCount: true,
            }}
            placeholder="请输入用户手机号"
          />
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={24}>
          <ProFormTreeSelect
            name="deptId"
            label="管辖科室"
            placeholder="请选择管辖科室"
            allowClear
            request={async () => {
              const res = await deptList({});
              if (res?.code === 200) {
                return res.data;
              } else {
                return [];
              }
            }}
            fieldProps={{
              filterTreeNode: true,
              treeDefaultExpandAll: true,
              fieldNames: {
                label: "deptName",
                value: "deptId",
              },
              onSelect:handleSelectDept,
            }}
          />
        </Col>
      </Row>
      {/* <Row gutter={20}>
        <Col span={24}>
          <ProFormSelect
            name="roleIds"
            label="归属角色"
            placeholder="请选择归属角色"
            allowClear
            mode="multiple"
            request={async () => {
              const res = await roleList({});
              if (res?.code === 200) {
                return res.data.map((its:any) => {
                  return {
                    label:its.roleName,
                    value:its.roleId
                  }
                });
              } else {
                return [];
              }
            }}
          />
        </Col>
      </Row> */}
    </ModalForm>
  );
});

export default ItemOption;
